<template>
    <div class="order-management">
        <h1>订单管理</h1>
        <div class="filters">
            <!-- 搜索和筛选区域 -->
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="formInline.searchOrderId" placeholder="请输入订单编号"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="formInline.searchStatus" placeholder="选择状态">
                        <el-option v-for="status in orderStatusOptions"
                                   :value="status.value"
                                   :key="status.value">
                            {{ status.label }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <div class="date-range">
                        <input type="date" v-model="startDate" @change="fetchOrders" />
                        <span>至</span>
                        <input type="date" v-model="endDate" @change="fetchOrders" />
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchOrder">查询</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 订单表格 -->
        <table>
            <thead>
            <tr>
                <th @click="sortBy('orderId')">订单号
                    <span v-if="sortField === 'orderId'">{{ sortOrder === 'asc' ? '↑' : '↓' }}</span>
                </th>
                <th>客户名</th>
                <th>地址</th>
                <th @click="sortBy('totalAmount')">总金额
                    <span v-if="sortField === 'totalAmount'">{{ sortOrder === 'asc' ? '↑' : '↓' }}</span>
                </th>
                <th>状态</th>
                <th @click="sortBy('createTime')">创建时间
                    <span v-if="sortField === 'createTime'">{{ sortOrder === 'asc' ? '↑' : '↓' }}</span>
                </th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="o in paginatedOrders" :key="o.id">
                <td>{{ o.id }}</td>
                <td>{{ o.users.username }}</td>
                <td>
                    <span class="address-text">{{ formatProvinceCityDistrict(o.merchants.address) }},{{o.merchants.addressDetail}}</span>
                </td>
                <td>¥{{ o.totalAmount.toFixed(2) }}</td>
                <td>
                    <span :class="['status-tag', getStatusClass(o.status)]">
                        {{ getStatusText(o.status) }}
                    </span>
                </td>
                <td>{{ formatDate(o.orderTime) }}</td>
                <td>
                    <button @click="viewOrder(o)">查看</button>
                </td>
            </tr>
            </tbody>
        </table>

        <!-- 分页控件 -->
        <div class="block">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="current"
                :page-sizes="pageList"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <!-- 订单详情弹窗 -->
        <div v-if="showDialog" class="dialog">
            <div class="dialog-content">
                <h2>订单详情</h2>

                <h3>订单商品</h3>
                <table class="items-table">
                    <thead>
                    <tr>
                        <th>商品名称</th>
                        <th>单价</th>
                        <th>数量</th>
                        <th>小计</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="item in currentOrder" :key="item.products.name">
                        <td>{{ item.products.name }}</td>
                        <td>¥{{ item.price.toFixed(2) }}</td>
                        <td>{{ item.sum }}</td>
                        <td>¥{{ (item.price * item.sum).toFixed(2) }}
                        </td>
                    </tr>
                    </tbody>
                </table>

                <div class="dialog-actions">
                    <button @click="showDialog = false">关闭</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {regionData,  codeToText} from 'element-china-area-data'
export default {
    data() {
        return {
            formInline: {
                searchOrderId: '',
                searchStatus: ''
            },
            //显示所有状态
            orderStatusOptions: [
                { value: '', label: '所有状态' },
                { value: '0', label: '未发货' },
                { value: '1', label: '待取货' },
                { value: '2', label: '已完成' },
                { value: '3', label: '已取消' }
            ],

            //订单数组
            paginatedOrders:[],

            orders: [],
            filteredOrders: [],
            searchQuery: '',
            filterStatus: '',
            startDate: '',
            endDate: '',

            //分页组件
            current:1,
            pageSize:8,
            pageList:[8,16,24],
            total:0,
            vo:{},

            //省市级联组件
            regionData: regionData,
            CodeToText: codeToText, // 将 CodeToText 存入 data 中

            sortField: 'createTime',
            sortOrder: 'desc',
            showDialog: false,

            //点击查看时
            currentOrder: [],
        }
    },

    created() {
        this.fetchOrders()
    },
    methods: {
        searchOrder(){
            this.vo = this.formInline
            this.fetchOrders()


        },
        // 格式化省市区地址
        formatProvinceCityDistrict(codes) {
            if (!codes) return ''

            const codeArray = typeof codes === 'string' ? codes.split(',') : codes
            if (codeArray.length < 3) return codes

            const [provinceCode, cityCode, districtCode] = codeArray
            const province = this.CodeToText[provinceCode] || ''
            const city = this.CodeToText[cityCode] || ''
            const district = this.CodeToText[districtCode] || ''

            // 格式化为"XX省 XX市 XX区"
            return `${province} ${city} ${district}`.trim()
        },
        getStatusClass(status) {
            const classes = {
                0: 'status-pending',    // 未发货 - 橙色
                1: 'status-ready',     // 待取货 - 蓝色
                2: 'status-completed', // 已完成 - 绿色
                3: 'status-cancelled'  // 已取消 - 红色
            }
            return classes[status] || ''
        },
        getStatusText(status) {
            const statusMap = {
                0: '未发货',
                1: '待取货',
                2: '已完成',
                3: '已取消'
            }
            return statusMap[status] || '未知状态'
        },
        fetchOrders() {
            // 模拟API请求
            setTimeout(() => {
                this.$axios.post(`order/selectOrderItems/${this.current}/${this.pageSize}`,this.vo).then(r =>{
                    this.paginatedOrders = r.data.list
                    this.total = r.data.total
                    console.log(333,this.paginatedOrders)
                })

                // 应用筛选
                this.filterOrders()

                // 重置页码
                this.currentPage = 1
            }, 300)
        },
        filterOrders() {
            let result = [...this.orders]

            // 搜索筛选
            if (this.searchQuery) {
                const query = this.searchQuery.toLowerCase()
                result = result.filter(order =>
                    order.orderId.toLowerCase().includes(query) ||
                    order.customerName.toLowerCase().includes(query)
                )
            }

            // 状态筛选
            if (this.filterStatus) {
                result = result.filter(order => order.status == this.filterStatus)
            }

            // 日期筛选
            if (this.startDate) {
                const start = new Date(this.startDate)
                result = result.filter(order => new Date(order.createTime) >= start)
            }
            if (this.endDate) {
                const end = new Date(this.endDate)
                end.setHours(23, 59, 59, 999)
                result = result.filter(order => new Date(order.createTime) <= end)
            }

            // 排序
            result.sort((a, b) => {
                const field = this.sortField
                const order = this.sortOrder === 'asc' ? 1 : -1

                if (a[field] < b[field]) return -1 * order
                if (a[field] > b[field]) return 1 * order
                return 0
            })

            this.filteredOrders = result
        },
        sortBy(field) {
            if (this.sortField === field) {
                this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'
            } else {
                this.sortField = field
                this.sortOrder = 'asc'
            }
            this.filterOrders()
        },

        // 获取订单ID
        viewOrder(order) {
            this.showDialog = true
            this.$axios.post(`orderItems/selectOrderItemsId/${order.id}`).then(r =>{
                this.currentOrder = r.data

                console.log(222,this.currentOrder)
            })

        },
        formatDate(date) {
            return new Date(date).toLocaleString()
        },

        handleSizeChange(val) {
            this.pageSize = val
            this.fetchOrders()

        },
        handleCurrentChange(val) {
            this.current = val
            this.fetchOrders()
        }
    }
}
</script>

<style scoped>
.order-management {
    padding: 20px;
    font-family: Arial, sans-serif;
}

.filters {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    align-items: center;
}

.filters input, .filters select {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.filters button {
    padding: 8px 16px;
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.filters button:hover {
    background-color: #66b1ff;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
}

th, td {
    border: 1px solid #ddd;
    padding: 12px;
    text-align: left;
}

th {
    background-color: #f5f7fa;
    cursor: pointer;
}

th:hover {
    background-color: #e6e9ed;
}

.status-tag {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    color: white;
}

.status-pending { background-color: #e6a23c; }
.status-paid { background-color: #409eff; }
.status-shipped { background-color: #909399; }
.status-completed { background-color: #67c23a; }
.status-cancelled { background-color: #f56c6c; }

.pagination {
    display: flex;
    gap: 5px;
}

.pagination button {
    padding: 8px 12px;
    border: 1px solid #ddd;
    background-color: white;
    cursor: pointer;
}

.pagination button.active {
    background-color: #409eff;
    color: white;
    border-color: #409eff;
}

.dialog {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.dialog-content {
    background-color: white;
    padding: 20px;
    border-radius: 4px;
    max-width: 800px;
    width: 90%;
    max-height: 90vh;
    overflow-y: auto;
}

.dialog-actions {
    margin-top: 20px;
    text-align: right;
}

.dialog-actions button {
    padding: 8px 16px;
    margin-left: 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.dialog-actions button:first-child {
    background-color: #909399;
    color: white;
}

.dialog-actions button:nth-child(2) {
    background-color: #67c23a;
    color: white;
}

.dialog-actions button:last-child {
    background-color: #f56c6c;
    color: white;
}

.items-table {
    width: 100%;
    margin-top: 10px;
}

.items-table th, .items-table td {
    padding: 8px;
}

.order-info {
    margin-bottom: 20px;
}

.order-info p {
    margin: 8px 0;
}
</style>